package hz.mobileproject.pda.callroll.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIItemListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Observer;

import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.net.NetError;
import cn.droidlover.xdroidmvp.router.Router;
import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.callroll.manger.CallRollByFaceDataMgr;
import hz.mobileproject.pda.callroll.manger.PhotoFaceLoaderMgr;
import hz.mobileproject.pda.callroll.manger.PhotoUpdateMgr;
import hz.mobileproject.pda.callroll.presenter.PCalroll;
import hz.mobileproject.pda.db.DBManager;
import hz.mobileproject.pda.entity.PrisonerPicBean;
import hz.mobileproject.pda.entity.request.Request_Callroll_loadCnf;
import hz.mobileproject.pda.entity.request.Request_backToPrison;
import hz.mobileproject.pda.entity.request.Request_calling;
import hz.mobileproject.pda.entity.request.Request_end;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.request.Request_loadPrisonerList;
import hz.mobileproject.pda.entity.request.Request_loadSubPrison;
import hz.mobileproject.pda.entity.request.Request_loadType;
import hz.mobileproject.pda.entity.request.Request_rollcall_close;
import hz.mobileproject.pda.entity.request.Request_start;
import hz.mobileproject.pda.entity.response.Response_callRoll_dept;
import hz.mobileproject.pda.entity.response.Response_callRoll_loadType;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPrisonerList;
import hz.mobileproject.pda.entity.response.Response_loadSubPrison;
import hz.mobileproject.pda.entity.response.Response_start;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.push.mqtt.MqttClientMgr;
import hz.mobileproject.pda.ui.adapter.ClearPersonAdapter;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;
import hz.mobileproject.pda.utils.HttpRqUtils;
import hz.mobileproject.pda.utils.VirateUtil;

/**
 * Created by Administrator on 2017/7/11 0011.
 * 电子点名界面
 */

public class CallrollActivity extends XActivity<PCalroll> implements IShowBarcodeStr {

    private String cusNumber;//机构号
    private String Poilce_id;
    private Boolean On_off;

    public static final String LoadCnf = "loadCnf";
    private HandleBroadcast handleBroadcast;
    private SoundPool soundpool;
    private int soundid;
    private Gson gson;
    private String callroll_data;
    private SPUtils spUtils;
    private SPUtils spUtils_cusNumber;
    private DBManager dBManager;
    private LoadingDialog loadingDialog;
    private Response_loadPoliceInfo loadPoliceInfo;
    //    private Response_loadCnf response_loadCnf;
    private Response_start response_start;
    private List<Response_loadPrisonerList> prisonersBeanList;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private ClearPersonAdapter mAdapter;
    private TextView tv_yingdian;
    private TextView tv_title_assets;
    private TextView tv_getNum;
    private int Numget;
    private TextView tv_name;
    private TextView tv_pici;
    private TextView tv_policeName;
    private TextView tv_code;
    private Request_calling callrolling;
    private TextView tv_zongshu;
    private Response_loadPrisonerList response_loadPrisonerList;
    private Bundle bundle;
    private Observer onLoginSucessObserver;
    private String cusnumber;

    private boolean isOnce = true;
    private boolean isUP = true;
    private List list;
    private Bundle bundles;

    private String addTempFlow_prison;
    private String addTempFlow_prisonName;

//    private InitPhotoHandler mHandler = new InitPhotoHandler();


    private final int NUMGET = 0;
    private final int NUMGET2 = 1;
    private Request_loadType request_loadType;
    private List<Response_callRoll_loadType> response_callRoll_loadType;
    private List<Response_callRoll_dept> response_callRoll_dept;
    private String addTempFlow_Key;
    private int data_getDeptId;
    private String data_getDeptKey;
    private String data_getDeptName;
    private String record_Id;
    private AlertDialog mAlertDialog;
    private WifiManager mWifiManager;
    private String mNetMac;
    private String data_policeName;
    private String data_policeId;
    //专门用于 防止名单中不同的点名 调用的接口
    private List<Response_loadPrisonerList> backRongPrisionList;

    //    private CheckFaceResultReceiver mCheckFaceResultReceiver;
    private int mintBatchCode;
    private Intent pushIntent;
    private boolean mbIsLoadFaceFinish;
    private PushReceiver mPushReceiver = new PushReceiver();


    private static final int SCAN_RESULT_OK = 0xA1;
    private static final int REQUEST_CODE_POLICE = 0x1055;


    private Button bt_end;


    /**
     * 推送信息广播接收
     */
    class PushReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(MqttClientMgr.ACTION_CONNECTION_LOST)) {
            } else if (intent.getAction().equals(MqttClientMgr.ACTION_MESSAGE_ARRIVED)) {
                try {
                    LogUtils.e("点名收到推送");
                    String msgContent = intent.getStringExtra("content");
                    JSONObject msg = new JSONObject(msgContent);
                    String type = msg.getString("push_type");
                    String push_data = msg.getString("push_data");
                    String push_user = msg.getString("push_user");
                    if (push_user.equals(MqttClientMgr.CLIENT_ID)) {
                        LogUtils.e("点名user和clientid相同");
                        return;
                    }
                    if (type.equals("1066")) {//点名推送
                        //[{"callTime":"2017-08-09 18:32:17","cusNumber":"3223","departmentId":"74","departmentName":"五监区一分监区","policeCode":"3304144","policeName":"程栋","prisonType":"1","prisonerId":"3350018324","prisonerName":"张明","recordId":"1015115","uploadTime":"2017-08-09 18:32:17"}]

                        JSONArray array = new JSONArray(push_data);
                        JSONObject jsonObject = array.getJSONObject(0);

                        String id = jsonObject.getString("prisonerId");
                        String prisonerName = jsonObject.getString("prisonerName");
                        String departmentName = jsonObject.getString("departmentName");
                        String departmentId = jsonObject.getString("departmentId");
                        String prisonType = jsonObject.getString("prisonType");


                        removeCallBean(id, prisonerName);


                    } else if (type.equals("1086") || type.equals("1076") || type.equals("1096")) {

                        CallrollActivity.this.finish();


                    } else if (type.equals("1067")) {   //临时流动
                        JSONObject jsonObject = new JSONObject(push_data);
                        String prisonerId = jsonObject.getString("prisonerId");
                        String prisonerName = jsonObject.getString("prisonerName");

                        removeCallBean(prisonerId, prisonerName);


                    } else if (type.equals("1068")) {    //10月16日增加 服务器主动推送  则调用调用接口
                        JSONObject jsonObject = new JSONObject(push_data);
                        String prisonerId = jsonObject.getString("prisonerId");
                        String prisonerName = jsonObject.getString("prisonerName");

                        removeCallBean(prisonerId, prisonerName);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    LogUtils.e("点名参数解析不对，走异常");
                }
            }
        }
    }

    /**
     * 人脸比对结果广播接收器
     */
//    class CheckFaceResultReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            switch (intent.getAction()) {
//                case "checkFaceSuccess":
//                    //TODO 上传犯人点名数据
//                    Response_loadPrisonerList prisoner = CallRollByFaceDataMgr.getInstance()
//                            .getPrisonerListItemById(intent.getStringExtra("prisonerId"));
//                    if (Constance.isNeiMeng) {
//                        ToastUtils.showLong("点名成功（" + prisoner.getPrisoner_name() + "），请转至下一位");
//                    } else {
//                        ToastUtils.showShort(prisoner.getPrisoner_name());
//                    }
//                    removeCallBean(prisoner.getPrisoner_id(), prisoner.getPrisoner_name());
//                    //滴的声音w
//                    soundpool.play(soundid, 1, 1, 0, 0, 1);
//                    send_calling(prisoner, 1);
//                    Numget++;
//                    tv_getNum.setText(String.valueOf(Numget));
//                    break;
//                case "checkHaveBeen":
//                    //已经点过
//                    break;
//                case "callPolice":
//                    break;
//                default:
//                    break;
//            }
//        }
//    }

    /**
     * 更新加载图片的主线程回调
     */
//    class InitPhotoHandler extends Handler {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            int curr = msg.arg1;
//            int size = msg.arg2;
//
//            switch (msg.what) {
//                case PhotoFaceLoaderMgr.MESSAGE_WHAT_LOAD_FINISH:
//                    loadingDialog.dismiss();
//                    mbIsLoadFaceFinish = true;
//                    //TODO 点名准备工作已经完成，开始点名
//                    ToastUtils.showLong("开始点名");
//                    startActivity(new Intent(CallrollActivity.this
//                            , CallRollByFaceOpenGlActivity.class));
//                    break;
//                case PhotoFaceLoaderMgr.MESSAGE_WHAT_LOAD_ITEM:
//                    loadingDialog.setMessage("正在加载犯人脸型（" + curr + "/" + size + "）").show();
//                    break;
//                case PhotoFaceLoaderMgr.MESSAGE_WHAT_LOAD_NO_PHOTO:
//                    ToastUtils.showLong("没有需要点名的犯人");
//                    CallrollActivity.this.finish();
//                    break;
//                case PhotoUpdateMgr.MESSAGE_WHAT_UPDATE_START:
//                case PhotoUpdateMgr.MESSAGE_WHAT_UPDATE_ITEM:
//                    loadingDialog.setMessage("正在更新图片（" + curr + "/" + size + "）").show();
//                    break;
//                case PhotoUpdateMgr.MESSAGE_WHAT_UPDATE_FINISH:
//                    //TODO 开始加载人脸数据
//                    PhotoFaceLoaderMgr.getInstance(CallrollActivity.this.getApplicationContext())
//                            .initPhoto(mHandler
//                                    , PhotoUpdateMgr
//                                            .getInstance(CallrollActivity.this.getApplicationContext())
//                                            .getLoadPhotoList());
//                    break;
//                default:
//                    break;
//            }
//        }
//    }


    public static void launch(Activity activity, String cnf) {
        Router.newIntent(activity)
                .to(CallrollActivity.class)
                .putString("LoadCnf", cnf)
                .launch();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_callroll;
    }

    @Override
    public PCalroll newP() {
        return new PCalroll(context);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        tv_yingdian = (TextView) findViewById(R.id.tv_yingdian);//应点
        tv_zongshu = (TextView) findViewById(R.id.tv_title_sum);//总数
        tv_title_assets = (TextView) findViewById(R.id.tv_title_assets);
        tv_getNum = (TextView) findViewById(R.id.tv_getNum);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_pici = (TextView) findViewById(R.id.tv_pici);
        tv_policeName = (TextView) findViewById(R.id.tv_policeName);
        tv_code = (TextView) findViewById(R.id.tv_code);
        //创建默认的线性LayoutManager
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        mRecyclerView.setHasFixedSize(true);
        response_loadPrisonerList = new Response_loadPrisonerList();
        prisonersBeanList = new ArrayList<Response_loadPrisonerList>();

        showPromptDlg();


        /*------------------------深圳演示，正式去掉---------------------------*/
        bt_end = (Button) findViewById(R.id.bt_end);
        if (Constance.isNeiMeng) {
            bt_end.setVisibility(View.VISIBLE);
        } else {
            bt_end.setVisibility(View.GONE);
        }
        bt_end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Request_end request_end = new Request_end();
                request_end.setCusNumber(cusNumber);
                request_end.setRecordId(record_Id);
                request_end.setUploadTime(TimeUtils.getNowString());
                request_end.setEndTime(TimeUtils.getNowString());
                request_end.setPoliceCode(Poilce_id);
                request_end.setEndModes("1");
                request_end.setHandEndReason("0");
                request_end.setPoliceId(loadPoliceInfo.getPolice_id());
                request_end.setClient_id(MqttClientMgr.CLIENT_ID);
                request_end.setDepartmentId(String.valueOf(data_getDeptId));
                callroll_data = gson.toJson(request_end);
                getP().getData(callroll_data, 8);
            }
        });

    }


    @Override
    public void initData(Bundle savedInstanceState) {
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        gson = new Gson();
        response_callRoll_loadType = new ArrayList<>();
        response_callRoll_dept = new ArrayList<>();
        //初始化广播
        initScan();

        Numget = 0;
        //对本地数据库的操作
        dBManager = DBManager.getInstance(getApplicationContext());

//        IMClientManager.getInstance(this).initMobileIMSDK();
//        IMClientManager.getInstance(this).getTransDataListener().setPush_Now(this);

        spUtils = SPUtils.getInstance("Callroll_loadCnf");
        spUtils_cusNumber = SPUtils.getInstance("app_login");

        cusNumber = spUtils_cusNumber.getString("cusnumber");
        //获取配置
        Request_Callroll_loadCnf callroll_loadCnf = new Request_Callroll_loadCnf();
        String nowTime = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        callroll_loadCnf.setCusNumber(cusNumber);
        callroll_loadCnf.setDate(nowTime);
        callroll_loadCnf.setTime(TimeUtils.getNowString());
        callroll_data = gson.toJson(callroll_loadCnf);
        //TODO 获取批次号
        getP().getData(callroll_data, 4);
        getP().getData(callroll_data, 10);
        //获取类型


        spUtils.put("loadCnf", nowTime);

        LogUtils.e(spUtils_cusNumber);

        if (!spUtils.getString("loadCnf").equals(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd")))) {
        }


        //注册消息的广播接受者
        mPushReceiver = new PushReceiver();
        try {
            IntentFilter pushfilter = new IntentFilter();
            pushfilter.addAction(MqttClientMgr.ACTION_CONNECTION_LOST);
            pushfilter.addAction(MqttClientMgr.ACTION_MESSAGE_ARRIVED);
            registerReceiver(mPushReceiver, pushfilter);
        } catch (Exception e) {
            mPushReceiver = null;
            e.printStackTrace();
        }

    }

    private void removeCallBean(String prisonerId, String prisonerName) {
        synchronized (CallrollActivity.class) {
            for (int i = prisonersBeanList.size() - 1; i >= 0; i--) {
                //相同表示已经点到    发给服务端某个人点到
                if (prisonerId.equals(String.valueOf(prisonersBeanList.get(i).getPrisoner_id()))) {
                    synchronized (CallrollActivity.class) {
                        mAdapter.removeBean(prisonersBeanList.get(i));


                        ToastUtils.showShort(prisonerName);
                        Numget++;
                        Message msgs = Message.obtain();
                        msgs.what = NUMGET;

                        msgs.obj = prisonerName;
                        handler.sendMessage(msgs);   //发送消息

                        Message msgs2 = Message.obtain();
                        msgs2.what = NUMGET2;


                        msgs2.obj = Numget;
                        handler.sendMessage(msgs2);   //发送消息

                        if (Constance.isNeiMeng) {
                            if (mAdapter.getCount() == 0) {
                                ToastUtils.showLong("点名成功，请按返回键退出");
                            }
                        }
                        break;
                    }
                }
            }
        }
    }




    private void initScan() {
//        initForLogin();
        handleBroadcast = new HandleBroadcast(this, this);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);

        /*--------------------------------2018/3/26日修改 可使用相机头进行民警扫码-----------------*/
        if (Constance.isNeiMeng) {
            if (CommonUtil.isCameraCanUse()) {
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_POLICE);
            } else {
                Toast.makeText(this, "请打开此应用的摄像头权限！", Toast.LENGTH_SHORT).show();
            }
        } else {

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != SCAN_RESULT_OK) {
            return;
        }
        //扫描结果回调
        Bundle bundle = data.getExtras();
        String scanStr = bundle.getString("qr_scan_result");
        if (requestCode == REQUEST_CODE_POLICE) {
            //获取民警信息
            getPoliceInfo(scanStr);   //返回的是带P的字符串
        }
    }

    @Override
    public void onWidgetClick(View view) {

    }


    @Override
    protected void onResume() {
        super.onResume();
        //开启广播接收扫描
        try {
            handleBroadcast.sendMyBroadcast();
        } catch (Error e) {
            e.printStackTrace();
            ToastUtils.showLong("没有检测到扫描头");
        }
        try {
            List<Request_end> endList = dBManager.queryRequest_ends();
            if (endList.size() != 0) {
                for (int i = 0; i < endList.size(); i++) {
//                    Request_end request_end = new Request_end();
//                    request_end.setCusNumber(endList.get(i).getCusNumber());
//                    request_end.setRecordId(endList.get(i).getRecordId());
//                    request_end.setUploadTime(endList.get(i).getUploadTime());
//                    request_end.setEndTime(endList.get(i).getEndTime());
//                    request_end.setEndModes("1");
//                    request_end.setHandEndReason("0");
                    Request_end request_end = endList.get(i);
                    callroll_data = gson.toJson(request_end);
                    getP().getData(callroll_data, 9);
                }

            }


            request_loadType = new Request_loadType();

           /* mAdapter = new ClearPersonAdapter(prisonersBeanList, this);
            mRecyclerView.setAdapter(mAdapter);*/


        } catch (Exception e) {
            Log.e(e.getMessage(), e.getMessage());
        }
    }

    /**
     * 点击条目后 显示下方的DialogUIUtils
     *
     * @param prisonid
     * @param strings
     */
    private void showView(final String prisonid, final String strings) {

        List<String> stringss = new ArrayList<>();

        for (int i = 0; i < response_callRoll_loadType.size(); i++) {
            stringss.add(response_callRoll_loadType.get(i).getValue());
        }
        LogUtils.e(strings);

        DialogUIUtils.showBottomSheetAndCancel(getApplicationContext(), stringss, "取消", new DialogUIItemListener() {
            @Override
            public void onItemClick(CharSequence text, int position) {
                //发送 夜护监
                Log.i("----", text + "" + response_callRoll_loadType.get(position).getKey());

                if (String.valueOf(text).equals("其他")) {
                    addTempFlow_Key = response_callRoll_loadType.get(position).getKey();
                    ///rollCall/loadDept
                    getP().getData(callroll_data, 12);
                } else {
                    //参数  1. 罪犯 id   2.民警id 3.类型
                    request_loadType.setPoliceId(loadPoliceInfo.getPolice_id());
                    request_loadType.setPoliceCode(Poilce_id);
                    request_loadType.setRecordId(record_Id);
                    request_loadType.setPoliceName(loadPoliceInfo.getPolice_name());
                    request_loadType.setPrisonerId(prisonid);
                    request_loadType.setPrisonerName(strings);
                    request_loadType.setDeptId(loadPoliceInfo.getDepartment_id() + "");
                    request_loadType.setDeptName(loadPoliceInfo.getDepartment_name() + "");
                    request_loadType.setFlowType(response_callRoll_loadType.get(position).getKey());
                    request_loadType.setClient_id(MqttClientMgr.CLIENT_ID);
                    callroll_data = gson.toJson(request_loadType);
                    sendAddTempFlow(callroll_data);
                }


            }

            @Override
            public void onBottomBtnClick() {
                Log.i("000", "onItemClick");
            }
        }).show();
    }

    private void sendAddTempFlow(final String callroll_data) {
        //弹出一个Dialog,确认

        mAlertDialog = new AlertDialog.Builder(CallrollActivity.this)
                .setTitle("提醒")
                .setIcon(R.mipmap.icon)
                .setMessage("确定流到夜护监吗?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getP().getData(callroll_data, 11);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mAlertDialog.dismiss();
                    }
                }).create();
        mAlertDialog.show();


    }

    private void showPromptDlg() {
        On_off = true;
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setMessage("请扫描民警二维码").show();
    }

    @Override
    public void updateText(String msg) {
        Log.e("扫描传过来的", msg);
        soundpool.play(soundid, 1, 1, 0, 0, 1);
        //判断传递过来的数据是否是民警      //机构号   6930159563092

        if (isOnce) {
            isOnce = !isOnce;
            getPoliceInfo(msg);

        } else {  //罪犯条码

            boolean flag = false;

            //点名数据
            synchronized (CallrollActivity.class) {
                for (int i = prisonersBeanList.size() - 1; i >= 0; i--) {

                    //相同表示已经点到    发给服务端某个人点到
                    if (msg.equals(String.valueOf(prisonersBeanList.get(i).getPrisoner_id()))) {

                        flag = true;

                        Numget++;
                        Message msgs = Message.obtain();
                        msgs.what = NUMGET;
                        msgs.obj = prisonersBeanList.get(i).getPrisoner_name();
                        handler.sendMessage(msgs);   //发送消息

                        Message msgs2 = Message.obtain();
                        msgs2.what = NUMGET2;
                        msgs2.obj = Numget;
                        handler.sendMessage(msgs2);   //发送消息

                        send_calling(prisonersBeanList.get(i), i);
                        LogUtils.e(i + "---" + prisonersBeanList.size());
                        mAdapter.removeBean(prisonersBeanList.get(i));
                        break;
                    }
                }
            }

            if (!flag) {

                if (backRongPrisionList == null || backRongPrisionList.size() == 0) {
                    ToastUtils.showLong("扫描两次民警条码");
                    return;
                }

                LogUtils.e(msg);
                for (int j = 0; j < backRongPrisionList.size(); j++) {
                    if (msg.equals(String.valueOf(backRongPrisionList.get(j).getPrisoner_id()))) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {   //被扫码罪犯不在点名名单中
                    //1 提示
                    ToastUtils.showLong(msg + " 罪犯不在点名名单中");
                    //2 振动
                    VirateUtil.vibrate(CallrollActivity.this, 2000);
                    //3 调接口
                    String time = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                    Request_backToPrison request_backToPrison = new Request_backToPrison(data_policeId, data_policeName, msg, data_getDeptId + "", data_getDeptName, time);
                    String request_backToPrision = gson.toJson(request_backToPrison);
                    getP().getData(request_backToPrision, 55);
                }
            }


        }

    }


    private void getPoliceInfo(String msg) {
        //获取民警基本信息
        Poilce_id = msg.contains("P") ? msg.substring(1) : msg;
        LogUtils.e("获取民警基本信息" + Poilce_id);
        Request_loadPoliceInfo callroll_loadPoliceInfo = new Request_loadPoliceInfo();
        callroll_loadPoliceInfo.setCusNumber(cusNumber);
        callroll_loadPoliceInfo.setPoliceCode(Poilce_id);  //3304281  一监区
        callroll_data = gson.toJson(callroll_loadPoliceInfo);
        //pushServer(Poilce_id,Poilce_id);
        getP().getData(callroll_data, 1);
    }

    private void send_calling(Response_loadPrisonerList response_loadPrisonerList, int i) {
        list = new ArrayList();
        Request_calling request_calling = new Request_calling();
        request_calling.setCusNumber(cusNumber);
        request_calling.setDepartmentName(response_loadPrisonerList.getDepartment_name());

        request_calling.setDepartmentId(String.valueOf(data_getDeptId));
        request_calling.setPrisonerId(response_loadPrisonerList.getPrisoner_id() + "");
        request_calling.setPrisonerName(response_loadPrisonerList.getPrisoner_name());
        request_calling.setCallTime(TimeUtils.getNowString());
        request_calling.setUploadTime(TimeUtils.getNowString());
        request_calling.setPrisonType(response_loadPrisonerList.getPrison_type() + "");
        request_calling.setRecordId(record_Id);
        request_calling.setPoliceName(loadPoliceInfo.getPolice_name());
        request_calling.setPoliceCode(Poilce_id);
        request_calling.setPoliceId(loadPoliceInfo.getPolice_id());
        request_calling.setClient_id(MqttClientMgr.CLIENT_ID);
        list.add(request_calling);
        callroll_data = gson.toJson(list);
        getP().getData(callroll_data, 7);
//        mAdapter.removeItem(response_loadPrisonerList);

    }

    //保存没有发送成功过的
    public void Error(NetError error, String getno, int i) {
        LogUtils.e(getno);

        switch (i) {
            case 7:   //
                try {
                    JSONArray mJsons = new JSONArray(getno);
                    JSONObject mJson = mJsons.getJSONObject(0);
                    Request_calling callrolling = new Request_calling();
                    callrolling.setCusNumber(mJson.getString("cusNumber"));
                    callrolling.setDepartmentName(mJson.getString("departmentName"));
                    callrolling.setDepartmentId(mJson.getString("departmentId"));
                    callrolling.setPrisonerId(mJson.getString("prisonerId"));
                    callrolling.setPrisonerName(mJson.getString("prisonerName"));
                    callrolling.setCallTime(mJson.getString("callTime"));
                    callrolling.setUploadTime(mJson.getString("uploadTime"));
                    callrolling.setPrisonType(mJson.getString("prisonType"));
                    callrolling.setRecordId(mJson.getString("recordId"));
                    callrolling.setPoliceName(mJson.getString("policeName"));
                    callrolling.setPoliceCode(mJson.getString("policeCode"));
                    callrolling.setPoliceId(mJson.getString("policeId"));

                    dBManager.insertcall(callrolling);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case 8:
                try {
                    JSONObject mJsono = new JSONObject(getno);

                    Request_end request_end = new Request_end();
                    request_end.setCusNumber(mJsono.getString("cusNumber"));
                    request_end.setRecordId(mJsono.getString("recordId"));
                    request_end.setUploadTime(mJsono.getString("uploadTime"));
                    request_end.setEndTime(mJsono.getString("endTime"));
                    request_end.setEndModes(mJsono.getString("endModes"));
                    request_end.setHandEndReason(mJsono.getString("handEndReason"));
                    request_end.setPoliceId(loadPoliceInfo.getPolice_id());
                    request_end.setClient_id(MqttClientMgr.CLIENT_ID);
                    request_end.setDepartmentId(String.valueOf(data_getDeptId));
                    dBManager.insertrequest_end(request_end);

                    Toast.makeText(this, "本次结束点名", Toast.LENGTH_SHORT).show();
                    this.finish();


                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
        }


    }

    //根据服务端的数据做不同操作
    public void respnose_data(String data_json, int type) {
        switch (type) {
            case 1://民警基本信息获取
                loadPoliceInfo = gson.fromJson(data_json, Response_loadPoliceInfo.class);
                data_policeName = loadPoliceInfo.getPolice_name();
                data_policeId = loadPoliceInfo.getPolice_id();

                data_getDeptId = loadPoliceInfo.getDepartment_id();
                data_getDeptName = loadPoliceInfo.getDepartment_name();

                //获取民警子部门
                Request_loadSubPrison request_loadSubPrison = new Request_loadSubPrison();
                request_loadSubPrison.setCusNumber(cusNumber);
                request_loadSubPrison.setDepartmentId(String.valueOf(data_getDeptId));
                callroll_data = gson.toJson(request_loadSubPrison);
                getP().getData(callroll_data, 2);

                dBManager.insertloadPoliceInfo(loadPoliceInfo);

                break;
            case 2:
                List<Response_loadSubPrison> loadSubPrisons = gson.fromJson(data_json, new TypeToken<List<Response_loadSubPrison>>() {
                }.getType());

                LogUtils.e("监区1" + "-----" + loadSubPrisons.size());

                if (loadSubPrisons != null && loadSubPrisons.size() > 1) {
                    //如果取得的监区 集合大于0  则让其选择
                    showWheelView(loadSubPrisons);
                } else {
                    send_start(loadSubPrisons.get(0).getDepartment_key());
                }

                break;
            case 3:
                tv_name.setVisibility(View.VISIBLE);
                tv_pici.setVisibility(View.VISIBLE);

                tv_policeName.setText(loadPoliceInfo.getPolice_name());
                tv_code.setText(String.valueOf(response_start.getBatch_code()));
//                mintBatchCode = response_loadCnf.getBatch_code();


                //2.1.3	根据部门编号获取需要点名的罪犯列表
                prisonersBeanList = gson.fromJson(data_json, new TypeToken<List<Response_loadPrisonerList>>() {
                }.getType());

                CallRollByFaceDataMgr.getInstance().setAllPrisonerList(prisonersBeanList);

                backRongPrisionList = new ArrayList<>();
                backRongPrisionList.addAll(prisonersBeanList);

                tv_yingdian.setText(prisonersBeanList.size() + "");
                //创建并设置Adapter

                mAdapter = new ClearPersonAdapter(prisonersBeanList);

                mAdapter.setOnAllTalkItemClickListener(new ClearPersonAdapter.OnAllTalkItemClickListener() {
                    @Override
                    public void onAllTalkItemClick(int position, View view, List<Response_loadPrisonerList> datas) {
                        // 夜监区  医院
//                        ToastUtils.showShort(position + "");
                        addTempFlow_prison = datas.get(position).getPrisoner_id();
                        addTempFlow_prisonName = datas.get(position).getPrisoner_name();
                        LogUtils.e(addTempFlow_prison + addTempFlow_prisonName + position);
                        //*******
                        showView(datas.get(position).getPrisoner_id(), datas.get(position).getPrisoner_name());

                    }
                });

                mRecyclerView.setAdapter(mAdapter);

                loadingDialog.dismiss();

                List<PrisonerPicBean> prisonerPicBeanList = new ArrayList<>();
//                //插入集合数据
//                dBManager.insertPrisonerPicBeanList(prisonerPicBeanList);
                break;
            case 4:  //获取的点名批次
                //在点名时间
//                if (data_json.equals("不在点名时间")) {
//                    loadingDialog.setMessage("不在点名时间").show();
//                    On_off = false;
//                } else {
//                    response_loadCnf = gson.fromJson(data_json, Response_loadCnf.class);
//                }
                break;

            //TODO 开始点名
            case 6:

                if (data_json.equals("已经点过名")) {
                    loadingDialog.setMessage("该时段已点过名").show();
                    On_off = false;
                } else {
                    response_start = gson.fromJson(data_json, Response_start.class);
                    mintBatchCode = response_start.getBatch_code();
                    record_Id = String.valueOf(response_start.getRecord_Id());
                    //2.1.3	根据部门编号获取需要点名的罪犯列表
                    Request_loadPrisonerList request_loadPrisonerList = new Request_loadPrisonerList();
                    request_loadPrisonerList.setCusNumber(cusNumber);
                    request_loadPrisonerList.setDepartmentId(String.valueOf(data_getDeptId));
                    request_loadPrisonerList.setDepartmentKey(data_getDeptKey);
                    request_loadPrisonerList.setRecordId(record_Id);
                    callroll_data = gson.toJson(request_loadPrisonerList);
                    getP().getData(callroll_data, 3);

                    //开始点名

//                    LogUtils.e(response_start.getRecord_Id() + "开始点名批次号" + response_start.getCall_total_num() + "");
                    tv_zongshu.setVisibility(View.VISIBLE);
                    tv_zongshu.setText(response_start.getCall_total_num() + "");
//                    loadingDialog.dismiss();
                    loadingDialog.setMessage("");
                }


                break;

            case 7:   //点名接口 返回

                /*----------------10月31日修改 ,end接口调用在本次谈话上传之后.未测试,故注释掉 --------------*/
                List list = dBManager.queryRequest_callingListRecordId(record_Id);  //查库
                if (list != null && list.size() > 0) {
                    //调用接口
                    String callroStr = gson.toJson(list);
                    getP().getData(callroStr, 7);
                    //删除本次数据
                    dBManager.deletecallingRecordId(list);
                }

                if (prisonersBeanList != null && prisonersBeanList.size() == 0) {
                    Request_end request_end = new Request_end();
                    request_end.setCusNumber(cusNumber);
                    request_end.setRecordId(record_Id);
                    request_end.setUploadTime(TimeUtils.getNowString());
                    request_end.setEndTime(TimeUtils.getNowString());
                    request_end.setPoliceCode(Poilce_id);
                    request_end.setEndModes("1");
                    request_end.setHandEndReason("0");
                    request_end.setPoliceId(loadPoliceInfo.getPolice_id());
                    request_end.setClient_id(MqttClientMgr.CLIENT_ID);
                    request_end.setDepartmentId(String.valueOf(data_getDeptId));
                    callroll_data = gson.toJson(request_end);
                    //调用end接口
                    getP().getData(callroll_data, 8);
                }

                break;

            case 8:   //调用end 接口返回
//
                this.finish();

                break;
            case 10:   //获取类型
                //{"key":"1","seq":1,"type_id":"CTF_FLOW_TYPE","type_name":"临时流动类型","type_seq":1,"value":"夜护监"}
                response_callRoll_loadType = gson.fromJson(data_json, new TypeToken<List<Response_callRoll_loadType>>() {
                }.getType());
                break;


            case 11:   //插入成功


                LogUtils.e(prisonersBeanList.size() + "");

                //点名数据
                synchronized (CallrollActivity.class) {
                    for (int i = prisonersBeanList.size() - 1; i >= 0; i--) {
                        //相同表示已经点到    发给服务端某个人点到
                        if (data_json.equals(String.valueOf(prisonersBeanList.get(i).getPrisoner_id()))) {
                            Numget++;
                            Message msgs = Message.obtain();
                            msgs.what = NUMGET;
                            msgs.obj = prisonersBeanList.get(i).getPrisoner_name();
                            handler.sendMessage(msgs);   //发送消息
                            ToastUtils.showShort("流动成功");
                            Message msgs2 = Message.obtain();
                            msgs2.what = NUMGET2;
                            msgs2.obj = Numget;
                            handler.sendMessage(msgs2);   //发送消息
                            mAdapter.removeBean(prisonersBeanList.get(i));
                            break;
                        }
                    }
                }


                /*----------------10月31日修改 ,end接口调用在本次谈话上传之后.未测试,故注释掉 --------------*/
                List list_liudong = dBManager.queryRequest_callingListRecordId(record_Id);  //查库
                if (list_liudong != null && list_liudong.size() > 0) {
                    //调用接口
                    String callroStr = gson.toJson(list_liudong);
                    getP().getData(callroStr, 7);
                    //删除本次数据
                    dBManager.deletecallingRecordId(list_liudong);
                }
                if (prisonersBeanList != null && prisonersBeanList.size() == 0) {
                    Request_end request_end = new Request_end();
                    request_end.setCusNumber(cusNumber);
                    request_end.setRecordId(record_Id);
                    request_end.setUploadTime(TimeUtils.getNowString());
                    request_end.setEndTime(TimeUtils.getNowString());
                    request_end.setPoliceCode(Poilce_id);
                    request_end.setEndModes("1");
                    request_end.setHandEndReason("0");
                    request_end.setPoliceId(loadPoliceInfo.getPolice_id());
                    request_end.setClient_id(MqttClientMgr.CLIENT_ID);
                    request_end.setDepartmentId(String.valueOf(data_getDeptId));
                    callroll_data = gson.toJson(request_end);
                    getP().getData(callroll_data, 8);

                }


                break;
            case 12:   //获取类型

                response_callRoll_dept = gson.fromJson(data_json, new TypeToken<List<Response_callRoll_dept>>() {
                }.getType());

                showViewDept(response_callRoll_dept);

                break;

            case 55:  //被扫码罪犯不在点名名单中


        }


    }

    /**
     * 流动
     *
     * @param response_callRoll_deptList
     */
    private void showViewDept(final List<Response_callRoll_dept> response_callRoll_deptList) {
        final List<String> strings = new ArrayList<>();
        for (int i = 0; i < response_callRoll_deptList.size(); i++) {
            strings.add(response_callRoll_deptList.get(i).getDept_name());
        }

        DialogUIUtils.showBottomSheetAndCancel(getApplicationContext(), strings, "取消", new DialogUIItemListener() {
            @Override
            public void onItemClick(CharSequence text, int position) {
                //发送 夜护监

                //参数  1. 罪犯 id   2.民警id 3.类型
                request_loadType.setPoliceId(Poilce_id);
                request_loadType.setPoliceName(loadPoliceInfo.getPolice_name());
                request_loadType.setPrisonerId(addTempFlow_prison);
                request_loadType.setPrisonerName(addTempFlow_prisonName);

                request_loadType.setDeptId(loadPoliceInfo.getDepartment_id() + "");
                request_loadType.setDeptName(loadPoliceInfo.getDepartment_name() + "");

                request_loadType.setFlowType(addTempFlow_Key);

                request_loadType.setIndeptId(response_callRoll_deptList.get(position).getDept_id() + "");
                request_loadType.setIndeptName(response_callRoll_deptList.get(position).getDept_name());


                callroll_data = gson.toJson(request_loadType);
                getP().getData(callroll_data, 11);

            }

            @Override
            public void onBottomBtnClick() {
                Log.i("000", "onItemClick");
            }
        }).show();

    }

    /**
     * loadSubPrison接口请求后, 弹窗让其选择是哪个监区的
     *
     * @param data
     */
    private void showWheelView(final List<Response_loadSubPrison> data) {

        final List<String> strings = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            strings.add(data.get(i).getDepartment_name());
        }

        LogUtils.e("监区2" + data.size());


        DialogUIUtils.showBottomSheetAndCancel(getApplicationContext(), strings, "取消", new DialogUIItemListener() {
            @Override
            public void onItemClick(CharSequence text, int position) {
                //发送 夜护监  //根据部门id  获取罪犯列表
                data_getDeptName = strings.get(position);
                data_getDeptId = data.get(position).getDepartment_id();
                data_getDeptKey = data.get(position).getDepartment_key();
                send_start(data_getDeptKey);
            }

            @Override
            public void onBottomBtnClick() {
                Log.i("000", "onItemClick");
            }
        }).show();


    }

    //开始点名
    public void send_start(String data_getDeptKey) {

        Request_start request_start = new Request_start();
        if (mWifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
            //获取被连接网络的mac地址
            mNetMac = wifiInfo.getBSSID();
        }
        LogUtils.e("wifi地址", mNetMac);
        request_start.setApMac(mNetMac);
        request_start.setCusNumber(cusNumber);//机构编号

        request_start.setDepartmentId(String.valueOf(data_getDeptId));//部门编号

        request_start.setDepartmentName(data_getDeptName);//部门名称
        request_start.setTime(TimeUtils.getNowString());//点名时间
        request_start.setPoliceCode(loadPoliceInfo.getPolice_code());
        request_start.setPoliceName(loadPoliceInfo.getPolice_name());
        request_start.setPoliceId(loadPoliceInfo.getPolice_id());
        request_start.setDepartmentKey(data_getDeptKey);
        callroll_data = gson.toJson(request_start);
        getP().getData(callroll_data, 6);
        //注册推送
        MqttClientMgr.getInstance(CallrollActivity.this.getApplicationContext())
                .subscribe("topic/" + String.valueOf(data_getDeptId) + "/call");
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
//        doLogout();
//        if(mCheckFaceResultReceiver != null){
//            unregisterReceiver(mCheckFaceResultReceiver);
//        }
        //结束消息接收器
        if (mPushReceiver != null) {
            unregisterReceiver(mPushReceiver);
        }
        //页面关闭 则断开推送
        MqttClientMgr.getInstance(CallrollActivity.this.getApplication())
                .unSubscribe("topic/" + String.valueOf(data_getDeptId) + "/call");
        //发送广播通知service关闭
        Intent stopIntent = new Intent();
        stopIntent.setAction("STOP");
        sendBroadcast(stopIntent);
        //检查当前批次本地数据库中是否有数据
        /*----------------10月31日修改 ,end接口调用在本次谈话上传之后.未测试,故注释掉 --------------*/
        List list = dBManager.queryRequest_callingListRecordId(record_Id);

        LogUtils.e("结束" + list.size());

        if (list.size() != 0) {
            callroll_data = gson.toJson(list);
            getP().getData(callroll_data, 7);

            dBManager.deletecallingRecordId(list);
        }


//        List list = dBManager.queryRequest_callingList();
//
//        LogUtils.e("结束" + list.size());
//
//        if (list.size() != 0) {
//            callroll_data = gson.toJson(list);
//            getP().getData(callroll_data, 7);
//
//            dBManager.deletecalling();
//        }

        if (handleBroadcast != null) {
            handleBroadcast.overBroadcastReceiver(this);
        }
    }

    //屏蔽返回键的代码:
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_HOME:
                return true;
            case KeyEvent.KEYCODE_BACK:
                sendCloseInterface();
                return true;
            case KeyEvent.KEYCODE_CALL:
                return true;
            case KeyEvent.KEYCODE_SYM:
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                return true;
            case KeyEvent.KEYCODE_STAR:
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 点击返回键调用手持机是否可以返回接口
     */
    private void sendCloseInterface() {
        Request_rollcall_close requestRollcallClose = new Request_rollcall_close();
        requestRollcallClose.setCus_number(cusNumber);
        requestRollcallClose.setRecord_id(record_Id);
        requestRollcallClose.setDept_id(data_getDeptId + "");
        requestRollcallClose.setDept_name(data_getDeptName);
        requestRollcallClose.setPolice_id(data_policeId);
        requestRollcallClose.setPolice_name(data_policeName);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.ROLLCALL_CLOSE, requestRollcallClose, rollCallColse);
    }

    CustomNetCallBack rollCallColse = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            //rtnCode为0。  0可以退出
            CallrollActivity.this.finish();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("点名未结束，请完成点名或通知指挥中心");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {

        }
    };


    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
//            int what = msg.what;
//            String getNum = String.valueOf(what);
//            tv_getNum.setText(getNum);
//            tv_title_assets.setText(msg.getData().getString("name"));
//            mAdapter.remove(msg.getData().getString("name"));
            super.handleMessage(msg);

            switch (msg.what) {
                case NUMGET: {
                    String pisonerName = (String) msg.obj;
                    LogUtils.e(pisonerName + "");

                    tv_title_assets.setText(pisonerName);
//            mAdapter.remove(msg.getData().getString("name"));
                }
                break;
                case NUMGET2: {
                    int num = (int) msg.obj;
                    tv_getNum.setText(num + "");

                }
                break;

            }
        }

    };

}
